//
//  YYECoursePlayViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2018/1/3.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYECoursePlayViewController.h"
#import "SPPageMenu.h"
#import "YYEIntroduceViewController.h"
#import "YYESectionViewController.h"
#import "YYECommentViewController.h"
#import "YYEAnswerViewController.h"
#import "YYEBaseViewController.h"
#import "FTPopOverMenu.h"
#import "YYECommentsViewController.h"
#import "YYELessonAnswerViewController.h"
#import "YYEWrongRecordViewController.h"
#import "YYEStudentViewController.h"
//#import "YYEPlayerView.h"


#import "HJVideoPlayerController.h"
#import "HJVideoPlayerHeader.h"
#import "HJVideoConst.h"

#import "SWFUIApplication.h"// 程序长时间未操作退出


@interface YYECoursePlayViewController () <SPPageMenuDelegate,UIScrollViewDelegate,YYEPlayerDelegate>

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) AliyunVodPlayer *aliPlayer;
@property (nonatomic,strong) UIImageView *backIV;


@property (nonatomic,strong) UIView *mainView;
//@property (nonatomic,strong) UIButton *playBtn;
//@property (nonatomic,strong) YYEPlayerView *playerV;

/** 视频播放器 */
@property (nonatomic, weak) HJVideoPlayerController *videoPlayerVC;

@property (nonatomic, strong) YYESectionViewController *secVC;

#define kHeight (SCREEN_WIDTH * 0.6 + kStartHeight)


@end

@implementation YYECoursePlayViewController

//- (void)dealloc {
//
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//
//
//}

// 重写
- (void)back {
    
    [self.videoPlayerVC.aliPlayer releasePlayer];

    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    [self configUI];

    
//    self.playerV = [[YYEPlayerView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 0.6)];
//    //    playerV.player = self.aliPlayer;
//    //    self.aliPlayer.autoPlay = YES;
//    [self.view addSubview:self.playerV];
    
    HJVideoPlayerController *videoPlayer = [[HJVideoPlayerController alloc]initWithFrame:CGRectMake(0, kStartHeight, kVideoScreenW, SCREEN_WIDTH * 0.6)];
    [self.view addSubview:videoPlayer.view];
    [self addChildViewController:videoPlayer];
    self.videoPlayerVC = videoPlayer;
    videoPlayer.cid = self.cid;
//    [self.videoPlayerVC setUrl:self.vid];
//    [self.videoPlayerVC setUrl:@"a66696f373844fa681a819ba5311d5d6"];
//    //    [self.videoPlayerVC setTitle:self.names[0]];
//    [self.videoPlayerVC setVideoTitle:@"天天吃鸡"];

    videoPlayer.topView.showListBlock = ^(UIButton *sender, UIEvent *event) {

        [self onNavButtonTapped:sender event:event];
    };
    
    if ([LoginModel shareLogin].role.integerValue == 1) {
        videoPlayer.topView.listBtn.hidden = YES;
    }
    
    if ([self.playback2 isKindOfClass:[NSNull class]]) {
        self.playback2 = @"0";
    }
    


    self.secVC.mid = self.mid;
    self.secVC.mid2 = self.mid2;

    
    self.videoPlayerVC.mid = self.mid;
    self.videoPlayerVC.mid2 = self.mid2;



}

-(void)applicationDidTimeout:(NSNotification *)notif {
    NSLog (@"超时要进行的操作");
    [self.videoPlayerVC.aliPlayer releasePlayer];
    
    [FTPopOverMenu dismiss];
    [self.navigationController popViewControllerAnimated:YES];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:kApplicationDidTimeoutNotification object:nil];
}




- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([LoginModel shareLogin].role.integerValue == 0) {

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidTimeout:) name:kApplicationDidTimeoutNotification object:nil];

    }
    
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];
    

    

}

// 收藏
-(void)onNavButtonTapped:(UIButton *)sender event:(UIEvent *)event {
    
    NSString *img = nil;
    if ([self.isCollect isEqualToString:@"0"]) {
        
        img = @"collection";
    }else if ([self.isCollect isEqualToString:@"1"]) {
        img = @"yyjy_73";
    }
    
    [FTPopOverMenu showFromEvent:event withMenuArray:@[@"收藏",@"评论",@"问答"] imageArray:@[@"collection",@"commend",@"answer"] doneBlock:^(NSInteger selectedIndex) {
        
        switch (selectedIndex) {
            case 0: // 收藏与取消收藏
            {
                NSDictionary *dic = @{
                                      @"username":[LoginModel shareLogin].username,
                                      @"uid":[LoginModel shareLogin].uid,
                                      @"token":[LoginModel shareLogin].token,
                                      @"cid":self.cid,
                                      @"del":self.isCollect
                                      };
                NSLog(@" --- %@",dic);
                [SVProgressHUD show];
                [AFNHelper post:LessonCollection parameters:dic success:^(id responseObject) {
                    
                    NSLog(@"%@",responseObject);
                    if ([responseObject[@"status"] isEqual:@1]) {
                        
                        if ([self.isCollect isEqualToString:@"0"]) {
                            NSLog(@"收藏成功");
                            self.isCollect = @"1";
                        }else if ([self.isCollect isEqualToString:@"1"]) {
                            NSLog(@"取消收藏");
                            self.isCollect = @"0";
                        }
                        
                    }
                    [SVProgressHUD showWithStatus:responseObject[@"message"]];
                    [SVProgressHUD dismissWithDelay:0.5];

                    
                } faliure:^(id error) {
                    
                    NSLog(@"请求失败");
                    [SVProgressHUD showWithStatus:ShowError];
                    [SVProgressHUD dismissWithDelay:0.5];
                    
                }];
                
            }
                break;
            case 1: {
                
                YYECommentsViewController *vc = [[YYECommentsViewController alloc]init];
                vc.cid = self.cid;
                [self.navigationController pushViewController:vc animated:YES];
                
            }
                break;
            case 2: {
                
                YYELessonAnswerViewController *vc = [[YYELessonAnswerViewController alloc]init];
                vc.cid = self.cid;
                [self.navigationController pushViewController:vc animated:YES];
                
            }
                break;
            default:
                break;
        }
        
    } dismissBlock:^{
        
    }];
    
}

- (void)configUI {
    
    NSArray *datas = nil;
    if ([LoginModel shareLogin].role.integerValue == 0) {
        
        datas = @[@"介绍",@"章节",@"习题",@"回答"];

    }
    else {
        datas = @[@"介绍",@"章节",@"回答",@"学生"];

    }
    
    
    SPPageMenu *pageMenu = [SPPageMenu pageMenuWithFrame:CGRectMake(0, kHeight, SCREEN_WIDTH, 40) trackerStyle:SPPageMenuTrackerStyleLine];
    pageMenu.selectedItemTitleColor = GeneralBlueColor;
    pageMenu.unSelectedItemTitleColor = LineColor;
    pageMenu.dividingLine.backgroundColor = [UIColor whiteColor];
    pageMenu.tracker.image = [UIImage imageNamed:@"bottomLine"];
    pageMenu.needTextColorGradients = NO;
    pageMenu.delegate = self;
    [self.view addSubview:pageMenu];
    
    YYEIntroduceViewController *introVC = [[YYEIntroduceViewController alloc]init];
    introVC.cid = self.cid;
    
    YYESectionViewController *secVC = [[YYESectionViewController alloc]init];
    secVC.delegate = self;
    self.secVC = secVC;
    self.secVC.cid = self.cid;
    self.secVC.isBuy = self.isBuy;
//    self.secVC.playback = self.playback;
//    self.secVC.mid = self.mid;

//    YYECommentViewController *comVC = [[YYECommentViewController alloc]init];
    YYEWrongRecordViewController *vc = [[YYEWrongRecordViewController alloc]init];
    vc.cid = self.cid;
    vc.mark = 1;
    
    YYEAnswerViewController *ansVC = [[YYEAnswerViewController alloc]init];
    ansVC.cid = self.cid;
    
    YYEStudentViewController *stuVC = [[YYEStudentViewController alloc]init];
    stuVC.cid = self.cid;
    
    [self addChildViewController:introVC];
    [self addChildViewController:secVC];

    
    if ([LoginModel shareLogin].role.integerValue == 0) {

        [self addChildViewController:vc];
        [self addChildViewController:ansVC];
    }
    else {
        [self addChildViewController:ansVC];
        [self addChildViewController:stuVC];
    }
    
    self.scrollView = [[UIScrollView alloc]init];
    self.scrollView.frame = CGRectMake(0, kHeight + 40, SCREEN_WIDTH, SCREEN_HEIGHT - kHeight - 40);
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    [self.scrollView addSubview:introVC.view];
    introVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kHeight - 40);
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 4, 0);
    
//    for (NSInteger i = 0; i < self.childViewControllers.count; i ++) {
//
//        YYEBaseViewController *baseVC = self.childViewControllers[i];
//        [self.scrollView addSubview:baseVC.view];
//
//        baseVC.view.frame = CGRectMake(SCREEN_WIDTH * i, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 190);
//        self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH * i, 0);
//        self.scrollView.contentSize = CGSizeMake(self.childViewControllers.count * SCREEN_WIDTH, 0);
//
//    }
    pageMenu.bridgeScrollView = self.scrollView;
    [pageMenu setItems:datas selectedItemIndex:1];
    
    
}

#pragma mark -- SPPageMenuDelegate
- (void)pageMenu:(SPPageMenu *)pageMenu itemSelectedAtIndex:(NSInteger)index {
    
    self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH * index, 0);
    
}

- (void)pageMenu:(SPPageMenu *)pageMenu itemSelectedFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    
    if (labs(toIndex - fromIndex) >= 2) {
        [self.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH * toIndex, 0) animated:NO];
    }else {
        [self.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH * toIndex, 0) animated:YES];
    }
    
    UIViewController *targetViewController = self.childViewControllers[toIndex];
    // 如果已经加载过，就不再加载
    if ([targetViewController isViewLoaded]) return;
    
    targetViewController.view.frame = CGRectMake(SCREEN_WIDTH * toIndex, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kHeight - 40);
    [self.scrollView addSubview:targetViewController.view];
    
}

#pragma mark -- UIScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
    
    UIViewController *targetViewController = self.childViewControllers[index];
    if ([targetViewController isViewLoaded]) return;
    
    self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH * index, 0);
    
    targetViewController.view.frame = CGRectMake(SCREEN_WIDTH * index, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kHeight - 40);
    [self.scrollView addSubview:targetViewController.view];
    
    
}

- (void)selectedVideoWithVideoID:(YYELittleChapterModel *)model clickSection: (NSInteger)clickSection currentSection: (NSInteger)currentSection clickPosition: (NSInteger)clickPosition currentPosition: (NSInteger)currentPosition  data:(NSArray *)data
{
//    self.backIV.hidden = YES;
    
    self.videoPlayerVC.datas = data;
    self.videoPlayerVC.clickSection = clickSection;
    self.videoPlayerVC.currentSection = currentSection;
    self.videoPlayerVC.clickPosition = clickPosition;
    self.videoPlayerVC.currentPosition = currentPosition;
    self.videoPlayerVC.playback = self.playback2;
    self.videoPlayerVC.mid3 = model.id;
    [self.videoPlayerVC setUrl:model.videoId];
    [self.videoPlayerVC setVideoTitle:model.videoTitle];

}


- (void)playOrPauseClicked:(UIButton *)button {
    
    button.selected = !button.selected;
    if (button.selected == YES) {
        [self.aliPlayer pause];
    }else {
        [self.aliPlayer resume];
    }
    
}




@end
